package com.ilovepostcard.utils;

import java.lang.ref.SoftReference;
import java.util.HashMap;

/**
 * When memory is very low, this cache will automatic recycle cached items.
 * 
 * @author Jerry
 * 
 * @param <Key>
 * @param <Resource>
 */
public class AutoRecycleCache<Key, Resource> {

    private HashMap<Key, SoftReference<Resource>> _cache;

    public AutoRecycleCache() {
        _cache = new HashMap<Key, SoftReference<Resource>>();
    }

    public synchronized Resource get(Key key) {
        if (!_cache.containsKey(key))
            return null;
        SoftReference<Resource> reference = _cache.get(key);
        if (reference == null) {
            _cache.remove(key);
            return null;
        }
        Resource resource = reference.get();
        if (resource == null) {
            _cache.remove(key);
        }
        return resource;
    }

    public synchronized void put(Key key, Resource resource) {
        _cache.put(key, new SoftReference<Resource>(resource));
    }

    public synchronized void clear() {
        _cache.clear();
    }

}